<template>
  <div id="userLoginPage">
    <h2 class="title">溯晞图库 - 用户登录</h2>
    <div class="desc">企业级智能协同云图库</div>
    <a-form :model="formState" autocomplete="off" @finish="handleSubmit">
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入用户邮箱!' }]">
        <a-input v-model:value="formState.userAccount" placeholder="请输入用户邮箱!" />
      </a-form-item>
      <a-form-item
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码!' },
          { min: 8, message: '密码不能小于8位!' },
        ]"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码！" />
      </a-form-item>
      <a-form-item name="code" :rules="[{ required: true, message: '请输入验证码!' }]">
        <a-space>
          <a-input
            v-model:value="formState.code"
            placeholder="请输入验证码!"
            style="width: 200px"
          />
          <div @click="refreshCaptcha" style="cursor: pointer">
            <img :src="captchaImgUrl" alt="验证码" height="32" />
          </div>
        </a-space>
      </a-form-item>
      <div class="tips">
        没有账号？
        <router-link to="/user/register">去注册</router-link>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" :loading="submitLoading" style="width: 100%"
          >登录</a-button
        >
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { userLoginUsingPost } from '../../api/userController'
import { useLoginUserStore } from '../../stores/useUserLoginStore'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'

interface FormState {
  userAccount: string
  userPassword: string
  code: string
}

const formState = reactive<FormState>({
  userAccount: '',
  userPassword: '',
  code: '',
})

const submitLoading = ref<boolean>(false)
const router = useRouter()
const loginUserStore = useLoginUserStore()

/**
 * 生成8位随机字符串作为验证码ID
 */
const generateCaptchaId = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < 8; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

const captchaId = ref<string>(generateCaptchaId())
const captchaImgUrl = ref<string>(
  `http://localhost:9494/api/user/login/getCaptcha?captchaId=${captchaId.value}`
)

/**
 * 刷新验证码
 */
const refreshCaptcha = () => {
  captchaId.value = generateCaptchaId()
  captchaImgUrl.value = `http://localhost:9494/api/user/login/getCaptcha?captchaId=${captchaId.value}`
}

/**
 * 提交表单
 * @param values
 */
const handleSubmit = async (values: any) => {
  submitLoading.value = true
  try {
    // 构建登录请求参数，添加captchaId
    const loginParams = {
      ...values,
      captchaId: captchaId.value,
    }

    const res = await userLoginUsingPost(loginParams)
    //登录成功，把登录态保存到全局状态中
    if (res.data.code == 0 && res.data.data) {
      await loginUserStore.fetchLoginUser()
      message.success('登录成功')
      router.push({
        path: '/',
        replace: true,
      })
    } else {
      message.error('登录失败，' + res.data.message)
      // 登录失败时自动刷新验证码
      refreshCaptcha()
    }
  } catch (e) {
    message.error('登录失败：' + e)
    // 登录失败时自动刷新验证码
    refreshCaptcha()
  } finally {
    submitLoading.value = false
  }
}

// 页面加载时初始化验证码
onMounted(() => {
  refreshCaptcha()
})
</script>
<style scoped>
#userLoginPage {
  max-width: 360px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  text-align: center;
  color: #bbb;
  margin-bottom: 16px;
}

.tips {
  text-align: right;
  font-size: 13px;
  color: #bbb;
  margin-bottom: 16px;
}
</style>
